<template>
  <div class="comment_list">
    <div class="comment_list_top">
      <div class="left" @click="showVConsole">
        <div class="top_font mr15">
          <span class="f17 fw500 blue">{{ totalData.scoreAvg || 0 }}</span
          ><span class="space7">/5</span>
        </div>
        <div class="top_font mr15">
          <span class="f14">{{ totalData.total }}条点评</span>
        </div>
      </div>
      <div class="right">
        <div class="comment_sort">
          <p
            v-for="item in sortOption"
            :key="item.text"
            :class="{ active: item.value === params.collation }"
            class="ml10"
            @click="sortList(item)"
          >
            {{ item.text }}
          </p>
        </div>
      </div>
    </div>
    <div class="comment_list_content">
      <List
        v-model:loading="loading"
        :finished="finished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <template v-for="item in lists" :key="item.surveyId">
          <CommentItem :item="item">
            <template #foot>
              <div class="active_area mt05">
                <div class="mt05" @click="handleJumpDetail(item)">
                  <span class="pr05">{{ item.commentTotal || 0 }}</span>
                  <van-icon name="comment-o" size="1.6rem" />
                </div>
                <div
                  v-if="commentAppraise.likeSwitch === 'Y'"
                  class="mt05 ml25"
                  @click="handlelike(item)"
                >
                  <span class="pr05">{{ item.likeTotal }}</span>
                  <van-icon
                    :color="isLikes(item) ? '#1989fa' : ''"
                    name="good-job-o"
                    size="1.6rem"
                  />
                </div>
              </div>
            </template>
          </CommentItem>
        </template>
      </List>
      <p v-if="!isMobile && !finished" class="pc_more" @click="onLoad">
        加载更多
      </p>
      <BackTop bottom="10vh" target=".comment_list_content" />
    </div>
    <div v-if="isComment" class="comment_list_btn">
      <Button block type="primary" @click="handleJump('H5CommentOn', route.query)">参与评论</Button>
      <!-- <Button block plain type="success" class="ml10" @click="shareSurvey()">分享</Button> -->
    </div>
  </div>
</template>

<script setup>
import {
  commentAccessLog,
  commentLike,
  getCommentLikeByUser,
  getDetail,
  getList,
  queryAvgScoreByCondition,
} from "@/server/business/comment.js";
import { apiCheckToken } from "@/server/business/survey.js";
import { commonStore } from "@/stores/common.js";
import { setWeappToken } from "@/utils/auth.js";
import {
  getDeviceInfo,
  getUrlQuery,
  goWxLogin,
  showVConsole,
  getSource,
  share
} from "@/utils/common.js";
import { storeToRefs } from "pinia";
import { BackTop, Button, List, showNotify } from "vant";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import CommentItem from "./component/commentItem.vue";

const commonStores = commonStore();
const { isMobile } = storeToRefs(commonStores);
const useQuery = getUrlQuery(); // href获取数据
const router = useRouter();
const route = useRoute();
const lists = ref([]);
const loading = ref(false);
const finished = ref(false);
const isComment = ref(false);
const likesId = ref([]);
const commentAppraise = ref({});
let userInfo = {};
let sysData = {};
let commentConfig = {};
let rateTitles = {};
const params = reactive({
  appraiseId: route.query.id,
  pageNum: 1,
  pageSize: 10,
  collation: "default",
  subjectId: route.query.subjectId || "",
  subjectId1: route.query.subjectId1 || "",
  subjectId2: route.query.subjectId2 || "",
  subjectId3: route.query.subjectId3 || "",
  subjectId4: route.query.subjectId4 || "",
  subjectId5: route.query.subjectId5 || "",
  subjectId6: route.query.subjectId6 || "",
  bizId: route.query.bizId || "",
});
const sortOption = [
  { text: "默认排序", value: "default" },
  { text: "最新排序", value: "lastTime" },
];
const totalData = reactive({
  total: 0,
  scoreAvg: 0,
});
// 去搜搜
const setSearch = () => {
  params.pageNum = 1;
  getSurveyList();
};
// 列表排序
const sortList = (item) => {
  params.collation = item.value;
  lists.value = [];
  setSearch();
};
// 异步更新数据
const onLoad = () => {
  getSurveyList();
  params.pageNum++;
};
// 获取列表
const getSurveyList = () => {
  getList(params).then((res) => {
    lists.value.push(...res.rows);
    totalData.total = res.total;
    loading.value = false; // 加载状态结束
    finished.value = lists.value.length >= res.total; // true 数据全部加载完成
  });
};
// 点赞 或 取消点赞
const handlelike = (item) => {
  if (!userInfo.pkMember)
    return showNotify({ type: "danger", message: "登录后才可以点赞!" }); // 没有用户信息 不能点赞
  let index = likesId.value.indexOf(item.commentId);
  let flag = index === -1 ? 0 : 1; // 0点赞 1取消点赞
  commentLike({
    ...sysData,
    likeby: userInfo.pkMember,
    appraiseId: route.query.id,
    commentId: item.commentId,
    delFlag: flag,
  }).then(() => {
    if (flag === 0) {
      item.likeTotal++;
      likesId.value.push(item.commentId);
    } else {
      item.likeTotal--;
      likesId.value.splice(index, 1);
    }
  });
};
// 是否已点赞
const isLikes = (item) => {
  return likesId.value.includes(item.commentId);
};
// 采集系统数据
const getSysData = () => {
  getSource().then((type) => {
    sysData.likeSource = type || "h5";
  });
  const mobileInfo = getDeviceInfo();
  sysData.browseType = mobileInfo.browseType;
  sysData.deviceType = mobileInfo.model;
  sysData.osVersion = mobileInfo.os;
};
// 跳转
const handleJump = (name, item) => {
  router.push({ name: name, query: { ...item } });
};
// 跳转评论
const handleJumpDetail = (item) => {
  router.push({
    name: "H5CommentDetail",
    query: { ...route.query, commentId: item.commentId },
  });
};
// 获取点评配置数据
const getCommentConfig = async () => {
  let res = await getDetail(route.query.id);
  commentConfig = res.data;
  rateTitles.title1 = commentConfig.appraiseConfig.scoreTitle1;
  rateTitles.title2 = commentConfig.appraiseConfig.scoreTitle2;
  rateTitles.title3 = commentConfig.appraiseConfig.scoreTitle3;
  rateTitles.title4 = commentConfig.appraiseConfig.scoreTitle4;
  rateTitles.title5 = commentConfig.appraiseConfig.scoreTitle5;
  isComment.value = res.data?.appraise?.involveType === "all";
  commentAppraise.value = res.data?.appraise;
};
// 获取综合平均值
const commentScoreAvg = async () => {
  let res = await queryAvgScoreByCondition({
    subjectId: route.query.subjectId || "",
    subjectId1: route.query.subjectId1 || "",
    subjectId2: route.query.subjectId2 || "",
    subjectId3: route.query.subjectId3 || "",
    subjectId4: route.query.subjectId4 || "",
    subjectId5: route.query.subjectId5 || "",
    subjectId6: route.query.subjectId6 || "",
    bizId: route.query.bizId || "",
  });
  totalData.scoreAvg = res.data;
};
// 获取登录用户对当前点评的点赞数据
const getLikes = () => {
  getCommentLikeByUser({
    appraiseId: route.query.id,
    likeby: userInfo.pkMember,
  }).then((res) => {
    likesId.value = res.data || [];
  });
};
// 根据token获取用户信息
const getUserInfo = async () => {
  if (useQuery.token && !["#token%23", "#token#"].includes(useQuery.token)) {
    setWeappToken(useQuery.token); // 存储用户token 用于加入接口的header
    let res = await apiCheckToken({ memberUserToken: useQuery.token });
    userInfo = res.data;
    getLikes();
  } else {
    getSource().then((type) => {
      if (type === "weapp") goWxLogin(); // 没有token 小程序跳登录
    });
  }
  addAccessLog();
};
// 添加访问量
const addAccessLog = () => {
  commentAccessLog({
    appraiseId: route.query.id,
    accessTime: new Date().getTime(),
    accessby: userInfo.pkMember,
    nickName: userInfo.name,
  });
};
// 分享
const shareSurvey = () => {
  let query = route.query;
  let search = "?";
  query.token = "#token#";
  for (let key in query) {
    search += key + "=" + query[key] + "&";
  }
  share(location.origin + location.pathname + search + "type=h5&isShare=y");
}
onLoad();
getUserInfo();
getCommentConfig();
commentScoreAvg();
getSysData();
</script>

<style scoped>
.comment_list {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: var(--van-gray-1);
}

.comment_list_top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 4.8rem;
  padding: 0 1.5rem;
  background: var(--van-white);
}

.comment_list_top .left {
  display: flex;
  align-items: center;
}

.comment_list_content {
  flex: 1;
  overflow-y: auto;
}

.comment_list_btn {
  padding: 1rem 1.5rem;
  display: flex;
}
.comment_list_btn .ml10{
  margin-left: 1rem;
}
.active_area {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 1.2rem;
  color: #999;
}

.active_area > div {
  display: flex;
  align-items: center;
}

.comment_sort {
  display: flex;
  align-items: center;
  color: var(--van-gray-6);
}

.comment_sort p.active {
  color: var(--van-blue);
}
</style>
